package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.PropertyConfigurator;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;


//import controller.main.Executer;

public class ChubJob implements Job {

	
	
	
	  public void execute(JobExecutionContext arg0) throws JobExecutionException{
	

		  System.out.println("Chub Job started at : "+new Date());
		    
		  try
	        {   
			  
	   Properties prop=new Properties();
	   prop.load(new FileInputStream(getJarDirectory()+File.separator+"scheduler_conf.properties"));
	   
	   System.out.println(prop.getProperty("chub_jar_path"));
	   System.out.println(prop.get("output_path"));
	   System.out.println(prop.get("error_path"));
	   System.out.println(prop.get("run_interval_in_milliseconds"));
	   
	
				
			  FileOutputStream fos = new FileOutputStream(prop.getProperty("output_path"));
			  FileOutputStream fos_error = new FileOutputStream(prop.getProperty("error_path"));
	            Runtime rt = Runtime.getRuntime();
	            Process proc = rt.exec("/usr/java6_64/bin/java -jar " + prop.getProperty("chub_jar_path") + " " + prop.getProperty("calling_parameters"));
	            // any error message?
	            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR",fos_error);            
	            
	            // any output?
	           StreamGobbler outputGobbler = new  StreamGobbler(proc.getInputStream(), "OUTPUT", fos);
	                
	            // kick them off
	            errorGobbler.start();
	            outputGobbler.start();
	          
	            System.out.println("New process started at "+ new Date());
	            
	            
	            // any error???
	            int exitVal ;
	           // synchronized (proc) {
	            	 exitVal = proc.waitFor();
	          //  }
	            
	            
	            /*
	             * Regarding the JavaWorld article, there is a bug with the final solution.
	             *  If a process terminates very quickly, errorGobbler and outputGobbler may not have yet run and consumed data.
	             *   The code should be: proc.waitFor(); errorGobbler.join(); outputGobbler.join();
	             * . This forced the main thread to wait until the streams finish reading input.
	             * */
	            errorGobbler.join(); 
	            outputGobbler.join();
	            
	            System.out.println("ExitValue: " + exitVal);
	            fos.flush();
	            fos.close(); 
	            
	            fos_error.flush();
	            fos_error.close();
	            
	        } catch (Throwable t)
	          {
	            t.printStackTrace();
	          }
		  
		 
		  System.out.println("Chub Job ended at : "+new Date());
	

		  
		  
		 // LoggerController.cronLogger.info("Cron Started successfully......");
		  //Ftp.main(null);
		//  Executer.executer();
		//  LoggerController.cronLogger.info("Cron finished successfully......");
	  }
	  
	  
	  
		public static String getJarDirectory()
		{
			
			String path = ChubJob.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		    String decodedPath;
		    String jarDir = "" ;
			try 
			{
				
				decodedPath = URLDecoder.decode(path, "UTF-8");
			    File jarFile = new File(decodedPath);
			    jarDir = jarFile.getParentFile().getPath();
			    
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		    return jarDir ;
		}
		
		
		
}